/*
 *  sparsematrix.cpp
 *  EPPI-0.0
 *
 *  Created by Juan Carlos García Orden on 07/07/2010.
 *
 */

#include "sparsematrix.h"

sparseMatrix::sparseMatrix(string nam)
:	n(0),
	ia(),
	ja(),
	values(),
	nnz(0),
	nrhs(1),
	typeName(nam)
{}

// ***

sparseMatrix::sparseMatrix(string nam, int nrow, int ncol)
:	n(0),
	ia(),
	ja(),
	values(),
	nnz(0),
	nrhs(1),
	typeName(nam)
{}

// ***

void sparseMatrix::resize(int& nrow, int& ncol)
{}

// ***

double sparseMatrix::readElement(int& row, int& col)
{
	int i;
	if(ja[col]==ja[col+1]){
		return 0.0;
	}
	else{
		for (i=ja[col];i<ja[col+1];++i){
			if (row==ia[i]){
				return values[i];
				break;
			}
		}
		return 0.0;
	}
}

// ***

double sparseMatrix::readElement(int& pos)
{
	return values[pos];
}

// ***

void sparseMatrix::writeElement(double val, int& row, int& col)
{
	// It is assumed that ia and ja are already created
	// and has C-style index (starting from 0)
	
	int i;
	for (i=ja[col];i<ja[col+1];++i)
	{
		if (row==ia[i])
		{
			values[i] = val;
			return;
		}
	}
}

// ***

void sparseMatrix::writeElement(double val, int& pos)
{
	values[pos] = val;
}

// ***

void sparseMatrix::reset(void)
{
	int i;
	for(i=0; i<nnz; ++i)	values[i]=0.0;
}

// ***

void sparseMatrix::sparsePattern(vector<int>& iia, vector<int>& jja)
{
	int i;
	
	nnz = iia.size();
	n = jja.size()-1;
	
	ia = new int[nnz];
	ja = new int[n+1];
	values = new double[nnz];
/*	
	if ( !(ia = intMalloc(nnz)) ) ABORT("Malloc fails for ia[].");
	if ( !(ja = intMalloc(jja.size())) ) ABORT("Malloc fails for ja[].");
	if ( !(values = doubleMalloc(nnz)) ) ABORT("Malloc fails for values[].");
*/	
	for (i=0; i<iia.size(); ++i)	ia[i] = iia[i]-1;
	for (i=0; i<jja.size(); ++i)	ja[i] = jja[i]-1;
	
	nrhs  = 1;
}

// ***

void sparseMatrix::setTypeName(string nam)
{
	typeName = nam;
}